<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use session;

class LoginController extends Controller
{
    //登录验证
	public function login(Request $request)
	{
		if($request->isMethod('post')){
			#如果提交数据则处理登录验证
			//$data = $request->input();
			#验证数据
			$result = $this->validate($request,[
				'username' => 'required',
				'password' => 'required',
				'captcha' => 'required|captcha'
			],[
				'username' => '请输入账号',
				'password' => '请输入密码',
				'captcha' => '验证码错误'
			]);
			
			# 通过数据和验证码之后，验证账号密码是否正确
			$user = DB::table('admin_user')->where(['username'=>$result['username'],'password'=>md5($result['password'])])->select('id','username','last_login_time','last_login_ip','group')->first();
			if($user){
				// session保存数据
				session(['admin_user'=>get_object_vars($user)]);
				// 更新用户登录时间和IP
				DB::table('admin_user')->where('id',$user->id)->update(['last_login_time'=>time(),'last_login_ip'=>get_real_ip()]);
				return redirect('/admin/index');
			} else {
				return redirect('/prompt')->with(['message'=>'账号或者密码错误','url' =>'/yqylogin', 'jumpTime'=>3,'status'=>'error']);
			}

		}
	}
	
	// 修改密码
	public function edit_pass(Request $request)
	{
		if($request->isMethod('post')){
			$mpass   = $request->input('mpass');
			$newpass = $request->input('newpass');
			# 验证原密码
			$res = DB::table('admin_user')->where(['password'=>md5($mpass),'username'=>session('admin_user.username')])->select('id')->first();
			if($res){
				# 修改密码
				DB::table('admin_user')->where('id',session('admin_user.id'))->update(['password'=>md5($newpass)]);
				return redirect('/yqylogin');
			}else{
				return redirect('/prompt')->with(['message'=>'原密码输入错误','url' =>'/admin/edit_pass', 'jumpTime'=>3,'status'=>'error']);
			}

		}
		return view('admin/edit_pass');
	}

	// 登出
	public function login_out(Request $request)
	{
		$request->session()->forget('admin_user');
		return redirect('/yqylogin');
	}
	
	
	
}
